package cluster

import (
	"context"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	"io/ioutil"
	. "k8s.io/kubernetes/panda/constant"
)

// 检查镜像是否存在
func CheckImageExist(imageName string, cli *client.Client) error {

	filters := filters.NewArgs()
	filters.Add("reference", imageName) //image:tag

	imageOpt := types.ImageListOptions{
		All:     true,
		Filters: filters,
	}
	images, err := cli.ImageList(context.Background(), imageOpt)
	if err != nil {
		return err
	}

	if len(images) == 0 {
		log.Info("This node not found image %s\r\n", imageName)
		log.Info("begin pull image %s\r\n", imageName)
		_, err := cli.ImagePull(context.Background(), imageName, types.ImagePullOptions{})
		if err != nil {
			return err
		}
	}
	return nil
}

//获取docker api url
func GetDockerApiUrl(host string) string {
	return "http://" + host + DOCKER_API_PORT
}

//容器与宿主机之间文件互传
func DockerCpFromContainerToHost(cli *client.Client, containerId string, src string, dest string) error {
	r, _, err := cli.CopyFromContainer(context.Background(), containerId, src)
	if err != nil {
		return err
	}

	content, err := ioutil.ReadAll(r)
	if err != nil {
		return err
	}
	if err := r.Close(); err != nil {
		return err
	}
	if string(content) != "content" {
		log.Info("expected content to be 'content', got %s", string(content))
	}
	return nil
}
